<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <!-- highlight-current 是否高亮选中节点 -->
        <!-- node-key 唯一标识字段 -->
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          :data="depts"
          default-expand-all
          :props="defaultProps"
          :expand-on-click-node="false"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="头像" width="80">
            <template #default="{ row }">
              <!-- 用户头像 -->
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <!-- 可选链 -->
              <span v-else class="username"> {{ row.username?.charAt(0) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" sortable label="手机号" />
          <el-table-column prop="workNumber" sortable label="工号" />
          <el-table-column prop="address" label="聘用形式">
            <template #default="{ row }">
              <span> {{ row.formOfEmployment === 1 ? '正式' : row.formOfEmployment === 2 ? '非正式' : '无' }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" sortable label="入职时间" />
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-button size="mini" type="text">
                <el-popconfirm title="确定删除该条数据吗？" @onConfirm="delEmployee(row.id)">
                  <el-button slot="reference" type="text" size="mini">删除</el-button>
                </el-popconfirm>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="ChangePage"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" />
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <!--
      roleIds 选中后的角色id数组
      roleList 所有可用角色列表
      -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="confirm">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartments } from '@/api/department'
import { listToTree } from '@/utils/index'
import { getEmployeeList, exportEmployee, delEmployee, getRoleList, getEmployeeDetail, assignRoles } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [{}],
      defaultProps: {
        children: 'children',
        label: 'name' // 标签文本字段
      },
      queryParams: {
        departmentId: null,
        pagesize: 10,
        page: 1,
        keyword: ''
      },
      total: 0,
      timer: null,
      tableData: [],
      showExcelDialog: false, // 控制 excel导入 弹层显示与隐藏
      showRoleDialog: false, // 控制 角色分配 弹层显示与隐藏
      roleList: [],
      roleIds: [],
      roleId: null
    }
  },
  created() {
    this.getDepts()
    this.getTableData()
  },
  methods: {
    // 确认按钮
    async confirm() {
      // 提交请求
      await assignRoles({ id: this.roleId, roleIds: this.roleIds })
      // 提示用户
      this.$message.success('分配成功')
      // 关闭弹层
      this.showRoleDialog = false
    },
    // 分配角色
    async btnRole(id) {
      // 显示弹层
      // this.showRoleDialog = true
      // 获取可用角色列表并赋值
      this.roleList = await getRoleList()
      // 获取点击员工id
      this.roleId = id
      // 获取已有权限id
      const { roleIds } = await getEmployeeDetail(id)
      // 赋值
      this.roleIds = roleIds
      // 显示弹层(提前显示弹层会导致弹层视图先出,后再选中权限的bug)
      this.showRoleDialog = true
    },
    // 删除员工
    async delEmployee(id) {
      await delEmployee(id)
      this.$message.success('删除成功')
      this.getTableData()
      if (this.tableData.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
    },
    // 导出excel
    async exportExcel() {
      const res = await exportEmployee()
      FileSaver.saveAs(res, '员工列表.xlsx')
    },
    // 获取部门列表
    async getDepts() {
      const res = await getDepartments()
      this.depts = listToTree(res, 0)
      this.queryParams.departmentId = this.depts[0].id // 记录首个节点的id
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
      })
    },
    // 获取点击部门的id
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
    },
    // 获取员工列表
    async getTableData() {
      const res = await getEmployeeList(this.queryParams)
      console.log(res, this.queryParams)
      this.tableData = res.rows
      this.total = res.total
    },
    // 切换页码
    ChangePage(newPage) {
      this.queryParams.page = newPage
      this.getTableData()
    },
    // 模糊搜索员工
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer的属性
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getTableData()
      }, 500)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
